const path = require('path');
const {
  override,
  fixBabelImports,
  addWebpackAlias,
  overrideDevServer,
  addPostcssPlugins,
  addLessLoader,
  addBabelPlugins
} = require('customize-cra');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const SimpleProgressWebpackPlugin = require('simple-progress-webpack-plugin')

const resolve = pathUrl => path.join(__dirname, pathUrl);

const addCustomize = () => config => {
  if (process.env.NODE_ENV === 'production') {
    // 关闭sourceMap
    config.devtool = false;
    // 配置打包后的文件位置
    // config.output.path = resolve('dist');
    // config.output.publicPath = './';
    // 添加js打包gzip配置
    config.plugins.push(
      new CompressionWebpackPlugin({
        test: /\.js$|\.css$/,
        threshold: 1024,
      }),
    )
    config.plugins.push(
      new UglifyJsPlugin({
        uglifyOptions: {
          compress: {
            drop_debugger: true,
            drop_console: true
          }
        },
        sourceMap: false,
        parallel: true
      })
    )
  }
  config.plugins.push(
    new SimpleProgressWebpackPlugin()
  )
  return config;
}

const devServerConfig = () => config => {
  return {
    ...config,
    proxy: {
      '/api': {
        target: 'https://xhc.shuiwu58.com',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/api',
        },
      }
    }
  }
}

module.exports = {
  webpack: override(
    addLessLoader({
      javascriptEnabled: true,
      modifyVars: { '@primary-color': '#7B82F4' }
    }),
    ...addBabelPlugins( // 支持装饰器
      [
        '@babel/plugin-proposal-decorators',
        { legacy: true }
      ]
    ),
    // 配置antd 的按需引入
    fixBabelImports('import', {
      "libraryName": "antd",
      "libraryDirectory": "es",
      "style": "css"
    }),
    // 配置路径访问快捷键
    addWebpackAlias({
      '@': resolve('src'),
      '@assets': resolve('src/assets'),
      '@components': resolve('src/components'),
      '@routes': resolve('src/routes'),
      '@store': resolve('src/store'),
      '@style': resolve('src/style'),
      '@utils': resolve('src/utils'),
      '@views': resolve('src/views'),
      '@api': resolve('src/api')
    }),
    // postCss 自动将px转为rem 需要配合 lib-flexible 使用
    addPostcssPlugins([
      require('postcss-pxtorem')({ rootValue: 100, propList: ['*'] })
    ]),
    // 压缩js等
    addCustomize()
  ),
  // 本地启动配置，可以设置代理
  devServer: overrideDevServer(
    devServerConfig()
  )
};